import argparse
from datetime import datetime, timedelta
from pathlib import Path
from loguru import logger

from src.services.arxiv_client import search_arxiv, download_pdfs
from src.services.filter_service import filter_articles
from src.services.read_service import read_articles
from src.services.summary_service import summarize_articles


def main(args):
    start_date = args.start_date
    end_date = args.end_date
    # Get the articles in physics.ao-ph category for the specified date range
    articles = search_arxiv(start_date, end_date)
    # Use LLM to filter articles related to AI
    selected_articles = filter_articles(articles, batch_size=args.batch_size, model=args.model)
    if not selected_articles:
        logger.warning("No articles selected after filtering. Will exit")
        return
    download_pdfs(selected_articles, output_dir=Path(args.pdf_dir))
    # Create a run_id as subdirectory name for distinguishing different runs
    timestamp = datetime.now().strftime("%Y%m%d_%H%M")
    logger.info(f"Start to read and summarize. Run ID: {timestamp}")
    output_dir = Path(args.ai_summary_dir) / timestamp
    read_articles(selected_articles, model=args.model, output_dir=output_dir)
    summarize_articles(selected_articles, model=args.model, output_dir=output_dir)
    logger.info(f"All done! All AI-generated content is saved in {output_dir.resolve()} as Markdown files")


if __name__ == "__main__":
    # Get current month's first and last day as defaults
    now = datetime.now()
    current_month_start = now.replace(day=1).strftime("%Y-%m-%d")
    # Get last day of current month
    if now.month == 12:
        next_month = now.replace(year=now.year + 1, month=1, day=1)
    else:
        next_month = now.replace(month=now.month + 1, day=1)
    current_month_end = (next_month - timedelta(days=1)).strftime("%Y-%m-%d")

    parser = argparse.ArgumentParser(description="ArXiv AI Weather Research Tool")
    parser.add_argument(
        "--start-date",
        type=str,
        default=current_month_start,
        help="The start date for the search in YYYY-MM-DD format (default: first day of current month)",
    )
    parser.add_argument(
        "--end-date",
        type=str,
        default=current_month_end,
        help="The end date for the search in YYYY-MM-DD format (default: last day of current month)",
    )
    parser.add_argument(
        "--batch-size", type=int, default=5, help="The number of papers sent to the LLM each time for filtering"
    )
    parser.add_argument(
        "--model", type=str, default="openai/gpt-4.1", help="The model to use for filtering and summarization"
    )
    parser.add_argument("--pdf-dir", type=str, default="./data/pdfs", help="The directory to save downloaded PDFs")
    parser.add_argument(
        "--ai-summary-dir", type=str, default="./data/summary", help="The directory to save AI-generated summaries"
    )
    args = parser.parse_args()
    main(args)
